package com.veeder.datacollection.config;

import java.net.InetSocketAddress;

import com.veeder.datacollection.config.ConnectionParam.ConnectionMode;
import com.veeder.datacollection.exception.ConfigurationException;

public class ConnParamConfig {
	
	public static ConnectionParam loadParams(String filename, String section) throws ConfigurationException{
		ConnectionParam connParam = new ConnectionParam();
		try {
			// parse the mode first.
			IniReader iniReader = new IniReader(filename);
			
			String modeStr = iniReader.getValue(section,
					"ConnectionMode");
			ConnectionMode mode = connParam.setMode(modeStr);

			// retrieve communication parameters
			// according to the connection mode configuration.
			if (mode.equals(ConnectionMode.TCPIP)) {
				String IPAddress = iniReader
						.getValue(section, "Host");
				int port = Integer.parseInt(iniReader.getValue(
						section, "Port"));
				InetSocketAddress socketAddress = new InetSocketAddress(
						IPAddress, port);
				connParam.setHostSocketAddress(socketAddress);
			} else if (mode.equals(ConnectionMode.SerialCommunication)) {
				SerialPortParam serialParam = new SerialPortParam();

				String portName = iniReader.getValue(section,
						"PortName");
				serialParam.setPortName(portName);

				String baudRate = iniReader.getValue(section,
						"BaudRate");
				serialParam.setBaudRate(baudRate);

				String parity = iniReader.getValue(section, "Parity");
				serialParam.setParity(parity);

				String databits = iniReader.getValue(section,
						"Databits");
				serialParam.setDatabits(databits);

				String stopbits = iniReader.getValue(section,
						"Stopbits");
				serialParam.setStopbits(stopbits);

				connParam.setSerialParam(serialParam);
			}

		} catch (Exception e) {
			throw new ConfigurationException(e);
		}
		return connParam;
	}
	
}
